/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.com.sixboy.listener;

import cn.com.sixboy.cache.Cache;
import cn.com.sixboy.cache.Property;
import cn.com.sixboy.cache.WebConfig;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;

/**
 *
 * @author sam.zheng <zcl1866@sina.com> 
 * @version <v0.1>
 * @date  2013-05-23 03:18:23
 * @copyright <sixboy>
 */
public class ServletInitListener implements ServletContextListener {

    static Logger log = Logger.getLogger(ServletInitListener.class);
    private Cache cache;
    private ServletContext context;
    @Override
    public void contextInitialized(ServletContextEvent sce) {
         this.cache = Cache.getInstance();
         initWebConfigToCache(sce);
         log.debug("SixBoyFrameWork Cache is Initialized");
        
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        cache.clear();
        log.debug("SixBoyFrameWork Cache is Destroyed");
    }
    /**
     * 初始化服务器相关参数到缓存中
     * @param sce 
     */
    private void initWebConfigToCache(ServletContextEvent sce){
         try {
             Properties props = new Properties();
             this.context = sce.getServletContext();         
             props.load(context.getResourceAsStream(context.getInitParameter(Property.WEB_INIT_CONFIG)));
             log.debug("SixBoyConfig is loading init success !!!");
             WebConfig config = new WebConfig();
             String[] filterFile = props.getProperty(Property.VALIDATE_LOGIN_PAGE).split("\\;");
             String[] validateApp = props.getProperty(Property.VALIDATE_APP).split("\\;");
             String appStyle = props.getProperty("appStyle")==null?Property.APP_STYLE:props.getProperty("appStyle");
             String header =  props.getProperty("appStyle.header")==null?Property.APP_STYLE:props.getProperty("appStyle.header");
             String footer =  props.getProperty("appStyle.footer")==null?Property.APP_STYLE:props.getProperty("appStyle.footer");
             config.setNoLoginFilterFile(filterFile);
             config.setValidateApp(validateApp);
             config.getAppStyleInfo().setAppStyle(appStyle);
             config.getAppStyleInfo().setHeader(header);
             config.getAppStyleInfo().setFooter(footer);
             cache.setConfig(config);
             log.debug("SixBoyFrame CacheModule is is init success !!!");
        } catch (IOException ex) {
             log.error(ex.getMessage(),ex);
        }
    }

}
